<?php
/*
Template Name: WPSPO modèle Défi
*/

get_header(); 

/* On va chercher les infos du défi */
$data = WPSPO_defis::get_options($post->ID);
$valueOptions = json_decode($data->defis_option_value);

// On vérifie si le défi pour un GROUPE a bien les renseignements
$typeSelected = get_post_meta(get_the_ID(), 'wpspo_typedefi', true); // Un groupe ?
//$asso_infos = get_user_meta($post->post_author, 'wpspo_asso_infos', true); // infos du groupe ok ?

/*if($typeSelected>1 && $asso_infos['asso_name']=='') {
    $activDefi = WPSPO_Defis::updateStatus($post->ID, 'pending');
    echo wpspo_redirection( get_permalink(WPSPO_ID_DEFIS).'/', "js" );
} elseif($typeSelected>1) {
    $defiGroupe = true;
    $activDefi = WPSPO_Defis::updateStatus($post->ID, 'publish');
}*/

if(get_option('wpspo_emails_settings')) { extract(get_option('wpspo_emails_settings')); }
$paramWpspoEmailSetting = get_option('wpspo_emails_settings');

/* Nombre de participant pour ce défi */
$countParticipant = WPSPO_Users::get_count($post->ID);

//print_r($data);
/*
 * Défi seul ?
 */
if(isset($valueOptions->share_defis) && $valueOptions->share_defis==1) {
    // Si le Share_defis est à 1, on affiche le formulaire
    $afficheForm = true;
} elseif($valueOptions->share_defis==null && $data->defis_id_user == $GLOBALS['current_user']->ID) {
    // Si le Share_defis est à 0 mais que c'est le créateur du défi, on affiche le formulaire
    $afficheForm = true;
} else {
    // Sinon on cache le formulaire
    $afficheForm = false; // par default
}

$coordonnees = explode("##", $valueOptions->coord_defis);
$lat = $coordonnees[0]; 
$lng = $coordonnees[1];

// Initialisation
$promesseEnCours = 0;
$promesseValide = 0;
$valideRecolte = false;
$add2Promesse = false;
$prommesseOk = 'Promesse NON Validée';

if( is_user_logged_in() ) {
    
    // Je vérifie si l'user a déjà fait une ou des promesses pour ce défi en vérifiant si il est déjà dans la base des participants
    $verification = WPSPO_Users::get_countUserByDefi($GLOBALS['current_user']->ID, $post->ID);
    //echo 'COUNT:'.$verification;
}


?>
<script type="text/javascript">
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display === 'none') {
            e.style.display = 'block';
        } else {
            e.style.display = 'none';
        }

    }

</script>
<div class="content" role="main">

    <?php if (have_posts()) : ?>
        <?php while (have_posts()) : the_post(); ?>
    
            <article <?php if( !empty( $rv['review'] ) ) echo $rv['review']; post_class('post-listing'); ?>>
                <div class="post-inner">
                    <header class="entry-header">
                        <h1 class="name post-title entry-title entry-title"><?php the_title(); ?></h1>
                    </header>

                    <div class="entry-content">

                        <?php
                        $idProjet = get_post_meta($post->ID, 'wpspo_choixprojets', true);
                        $projetStatus = get_post_status( $idProjet ); // Récupère le status du post
                        $projet = get_post($idProjet);

                        $auteurDefi = get_the_author();

                        ?>
                        <!-- Projet -->
                        <div style="margin-top:15px;">
                            <strong><?php _e('For this project', 'sponsorpress'); ?></strong><br /><a href="<?php echo get_permalink( $idProjet ); ?>"><?php echo $projet->post_title; ?></a>
                        </div>
                        
                        <!-- Description -->
                        <div style="margin-top:15px;">
                            <strong><?php _e('Description of challenge', 'sponsorpress'); ?></strong><div class="clear"></div>
                            <?php 
                             if( has_post_thumbnail() ) { ?>
                                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" ><?php the_post_thumbnail('thumbnail', array('class' => "alignleft wp-post-image")); ?></a>

                            <?php
                            } else {
                                // Si l'article n'a pas d'Image à la Une, on récupère la 1ère image attachée
                                $attachments = get_children(
                                    array(
                                    'post_parent' => get_the_ID(),
                                    'post_type' => 'attachment',
                                    'post_mime_type' => 'image',
                                    'orderby' => 'menu_order',
                                    'order' => 'DESC',
                                    'numberposts' => 1
                                    )
                                );
                                if( $attachments ) {
                                    foreach( $attachments as $attachment ) :
                                    ?>
                                    <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" ><?php echo wp_get_attachment_image($attachment->ID , 'thumbnail', '', array('class' => "alignleft wp-post-image")); ?></a>

                                    <?php
                                    endforeach;
                                }
                            }
                            ?>
                           <?php the_content(); ?>

                        </div>
                        <div class="clear"></div>
                        
                        <!-- Map -->
                        <?php if($paramWpspoSetting['affmaps']==1) { ?>
                            <div class="wpspo-fexible-container">
                                <?php echo do_shortcode('[wpspo_map address="'.$valueOptions->ville_defis.'" width="300px" height="250px"]'); ?>
                            </div>
                        <?php } ?>
                        <!-- Date -->
                        <div style="margin-top:15px;">
                            <strong><?php _e('Date of challenge', 'sponsorpress'); ?></strong><br /><?php echo wpspo_display_date($valueOptions->date_defis, $valueOptions->date_end_defis); ?>
                        </div>
                        <!-- Ville -->
                        <div style="margin-top:15px;">
                            <strong><?php _e('City', 'sponsorpress'); ?></strong><br /><?php echo $valueOptions->ville_defis; ?>
                        </div>
                        <!-- Informations -->
                        <div style="margin-top:15px;">
                            <strong><?php _e('Informations on this challenge', 'sponsorpress'); ?></strong><br />
                            <?php _e('Method of calculation donations', 'sponsorpress'); ?> :
                            <?php if($valueOptions->mode_defis==1) { 
                                printf( __('Donation Amount is %s by <b>%s</b>', 'sponsorpress'), get_wpspo_currency_symbol(), $valueOptions->text_mode_defis );
                            } else { 
                                _e('Fixed donation amount', 'sponsorpress');
                            }
                            ?>
                        </div>
                        

                        <!-- Auteur -->
                        <div id="wpspo-author-meta">
                            <?php _e('Challenge organized by ', 'sponsorpress'); ?> <a href="<?php echo get_permalink(WPSPO_ID_PARTICIPANTS).'?profil='.get_the_author_meta( 'user_nicename', get_the_author_id()).''; ?>"><?php echo $auteurDefi; ?></a>
                        </div>
                        
                        <!-- Nombre de participants -->
                        <div class="clear"></div>
                        
                        <!-- BOUTON PARTICIPER A CE DEFI -->
                        <a name="participate"></a>
                        <?php 
                            if($_GET['participate']==1) {
                                echo '<div class="clear espace10"></div><div class="wpspo-confirm">'.__('Your participation has been added', 'sponsorpress').'</div><div class="clear"></div>';
                            }
                            if( is_user_logged_in() ) {
                                if( $afficheForm==true ) {
                                    if( $verification==0 && $projetStatus=='publish' ) {
                                        
                                        echo '<div style="margin-top:15px;">
                                            <h1 class="name post-title entry-title entry-title">'.__('I want participate', 'sponsorpress').'</h1>
                                        </div>';

                                        if (isset($_GET['erreurparticipation'])) {

                                            echo '<div class="wpspo-erreur">';

                                                switch ($_GET['erreurparticipation']) {
                                                    case 'text' :
                                                        echo __("Please, enter you participate text", 'sponsorpress');;
                                                        break;                                                    
                                                    case 'privatecode' :
                                                        echo __("Sorry, the private code is not valid", 'sponsorpress');;
                                                        break;
                                                    default :
                                                        echo 'Une erreur est survenue.';

                                                }

                                            echo '</div>';

                                         } 
                                        ?>
                                        <div style="margin-top:25px;padding:10px;text-align: center;background-color:#E15821;color:#fff;">
                                            <form method="post" action="#participate">
                                                <?php wp_nonce_field('go-participate', 'security-participate'); ?>
                                                <p><?php _e('Thank you indicate why you want to join this challenge', 'sponsorpress'); ?></p>
                                                <textarea id="textparticipate" name="textparticipate"></textarea>
                                                <?php if($valueOptions->share_prive==1) { ?>
                                                    <p><?php _e('Please, enter the private code', 'sponsorpress'); ?></p>
                                                    <input type="text" value="" name="privatecode" /><br />
                                                <?php } ?>
                                                <input type="submit" name="submit-participate" value="<?php _e('I confirm', 'sponsorpress'); ?>" />
                                            </form>
                                        </div>
                            <?php  
                                    } else {
                                        echo '<div class="clear espace10">&nbsp;</div><strong>';
                                        printf( __('You already participant for this challenge. Visit %s to show your challenges, particicipates and promesses', 'sponsorpress'), '<a href="'.get_permalink(WPSPO_ID_COMPTE).'">'.__('your account', 'sponsorpress').'</a>');
                                        echo '.</strong>';
                                    }
                                }

                            } else {
                                //echo _e('To participate to this challenge, please log in.', 'sponsorpress');
                                echo '<div class="clear espace10">&nbsp;</div>';
                                echo '<div style="text-align:center;">';
                                if($post->post_status=='archive') {
                                    echo do_shortcode('[wpspobutton link="" content="'.__('This challenges is finish!', 'sponsorpress').'"]');
                                } else { 
                                    echo do_shortcode('[wpspobutton link="'.wp_login_url( get_permalink() ).'" content="'.__('To participate to this challenge, please log in.', 'sponsorpress').'"]');
                                }
                                echo '</div>';
                            }
                        ?>
                        </div>
                </article> 
                <div class="clear epsace10">&nbsp;</div>
        
                <article <?php if( !empty( $rv['review'] ) ) echo $rv['review']; post_class('post-listing'); ?>>
                    <div class="post-inner">
                         <header class="entry-header">
                            <h1 class="name post-title entry-title entry-title"><?php _e('List of participants', 'sponsorpress'); ?> (<?php echo $countParticipant; ?>)</h1>
                        </header>

                        <div class="entry-content">
                            
                            <!-- Formulaire de promesse -->
                            <a name="promesse"></a>
                            <p class="post-meta"></p>
                            <?php 
                                if( $_GET['sponsoriser'] == 1 ) {
                                    echo '<div class="wpspo-confirm">'.__('Your pledge has been added. Thanks!', 'sponsorpress').'</div>'; 
                                }
                                $listParticipant = WPSPO_Users::get_listByDefi($post->ID);

                                if($listParticipant) {

                                    echo '<div id="wpspo_table">
                                           <div class="wpspo_row">
                                              <span class="wpspo_cell1">'.__('Name/Organization/Group', 'sponsorpress').'</span>
                                            </div>';
                                    foreach ( $listParticipant as $participant ) {
                                        
                                        $auteurName = wspo_affiche_user($participant->users_id_user);
                                        $auteurAge = wspo_affiche_age($participant->users_id_user);
                                        $auteurImg = get_avatar($participant->users_id_user, 52);
                                   
                                        if($valueOptions->text_mode_defis!='' && $valueOptions->mode_defis==1) { 
                                            $textModeDefis = '/ '.$valueOptions->text_mode_defis;
                                        } 
                                        
                                        /* Va cherche les valeurs de chaque participant */
                                        $valueParticipant = json_decode($participant->users_option_value);
                                                                                
                                        /* Nb promesse par participant */
                                        $nbSponsor = WPSPO_Promesse::get_countParentByIdDefi($post->ID, $participant->users_id_user);
                                        $verifiDejaSponsor = WPSPO_Promesse::get_countByUser($GLOBALS['current_user']->ID, $participant->users_id_user, $post->ID);

                                        echo '<a name="'.$post->ID.$participant->users_id_user.'"></a>';
                                        echo '<div class="wpspo_row">
                                                  <span class="wpspo_cell"><a href="'. get_permalink(WPSPO_ID_PARTICIPANTS).'?profil='.get_the_author_meta( 'user_nicename', $participant->users_id_user).'">'.$auteurImg.'</a><b>'.$auteurName.'</b>';
                                        if($auteurAge) { echo ' ('.$auteurAge.' ans)'; } 
                                        
                                        echo '<div style="margin-top:3px;">';
                                        echo '<div style="width:65%;float:left;">'.stripslashes($valueParticipant->text).'</div>';

                                        if($nbSponsor>0) {
                                            $totalPromesse = WPSPO_Promesse::get_sumByUser($post->ID, $participant->users_id_user);
                                            echo '<div style="width:20%;float:left;background-color:#e15821;color:#fff;padding:3px;text-align:center;">';
                                            printf(_n("%s friend sponsors", "%s friends sponsors", $verifiDejaSponsor, 'sponsorpress'), $nbSponsor);
                                            echo '<br /><small>'.__('Pledge:', 'sponsorpress').' '.wpspo_price($totalPromesse).'</small></div>';
                                        } 
                                        echo '</div>';
                                            /* Si l'auteur du défi n'est pas un participant, on afficher le bouton pour le sponsorisé */
                                            if( $projetStatus=='publish' && is_user_logged_in() ) { 
                                                
                                                /* Si il n'a pas fait une promesse pour cet utilisateur */
                                                if($verifiDejaSponsor==0 && $participant->users_id_user!=$GLOBALS['current_user']->ID ) {
                                                    
                                                    /* On affiche un lien pour le sponsoriser */
                                                    echo "<br /><a href=\"javascript:void(0);\" onclick=\"toggle_visibility('sponsor_".$participant->users_id_user."');\" onfocus=\"this.blur()\" style=\"text-decoration:underline;\">";
                                                    printf(__('Sponsor %s?', 'sponsorpress'), wspo_affiche_user($participant->users_id_user, 0));
                                                    echo "</a>";
                                                    
                                                    /* Traitement des erreurs du formulaire */
                                                    if (isset($_GET['erreur'])) {
                                                        echo '<div class="alert">';
                                                            switch ($_GET['erreur']) {
                                                                case 'radin' :
                                                                    echo 'Vous ne pouvez pas faire une promesse inférieur à 0 €.';
                                                                    break;
                                                                case 'trop' :
                                                                    echo 'Nous n\'acceptons pas les promesses supérieurs à 10000 €.';
                                                                    break;
                                                                default :
                                                                    echo 'Une erreur est survenue.';
                                                            }
                                                        echo '</div>';
                                                    }
                                                    echo '<div id="sponsor_'.$participant->users_id_user.'" style="display:none;margin-top:10px;background-color:#007bc2;color:#fff;padding:8px;border-radius: 5px;">';
                                                    /* Formulaire pour le sponsoriser */
                                                    echo '<form method="post" name="sponsor_user_'.$participant->users_id_user.'" action="#promesse">';
                                                    echo wp_nonce_field('go-promesse', 'security-promesse');
                                                    echo '<input type="hidden" name="sponsor_user" value="'.$participant->users_id_user.'">';
                                                    if($valueOptions->mode_defis==1) {
                                                        _e('I want to give', 'sponsorpress');
                                                        echo ' <input type="text" size="10" name="promess_montant" id="promess_montant" value="" style="font-size: 14px;" /> '.get_wpspo_currency_symbol().' '.__('per', 'sponsorpress').' '.stripslashes($valueOptions->text_mode_defis);
                                                    } else {
                                                        
                                                        /* Sinon on affiche sa promesse */
                                                        _e('I make a fixed donation', 'sponsorpress');
                                                        echo ' <input type="text" size="10" name="promess_montant" id="promess_montant" value="" style="font-size: 14px;" />'.get_wpspo_currency_symbol();
                                                        

                                                    }
                                                    echo '<input type="checkbox" name="newletter" value="1" checked /> '.__('Subcribe to the project newletter?', 'sponsorpress').'<br /><br />';
                                                    echo ' <input type="submit" name="promesse-envoi" value="'.__('Validate your pledge', 'sponsorpress').'" />';
                                                    echo '</form></div>';

                                                } else if ( $participant->users_id_user==$GLOBALS['current_user']->ID && $post->post_status=='archive' ) {
                                                    
                                                    $testRealiseFloat = (float)$participant->users_realise;
                                                    if( empty($testRealiseFloat) ) {
                                                        
                                                        $msgFinish = __('Do you validate that?', 'sponsorpress');
                                                        /* Traitement des erreurs du formulaire */
                                                        if (isset($_GET['erreur_r'])) {
                                                            echo '<div class="clear"></div><div class="alert">';
                                                                switch ($_GET['erreur_r']) {
                                                                    case 'zero' :
                                                                        echo '<script language=javascript>alert("'.__('Your result should be greater than 0', 'sponsorpress').'")</script>';
                                                                        break;
                                                                    default :
                                                                        echo 'Une erreur est survenue.';
                                                                }
                                                            echo '</div>';
                                                        }
                                                        echo "<br /><a href=\"javascript:void(0);\" onclick=\"toggle_visibility('result_".$participant->users_id_user."');\" onfocus=\"this.blur()\" style=\"text-decoration:underline;\">".__('Enter your score', 'sponsorpress')."</a>";
                                                        echo '<div id="result_'.$participant->users_id_user.'" style="display:none;margin-top:10px;background-color:#007bc2;color:#fff;padding:8px;border-radius: 5px;">';
                                                        
                                                        /* Formulaire pour le sponsoriser */
                                                        echo '<form method="post" name="result_'.$participant->users_id_user.'" action="#'.$post->ID.$participant->users_id_user.'">';
                                                        echo wp_nonce_field('go-result', 'security-result');
                                                        echo __('I realized', 'sponsorpress').' <input type="text" size="5" name="result_num" id="result_num" value="" style="font-size: 14px;" /> '.stripslashes($valueOptions->text_mode_defis);
                                                        echo ' <input type="submit" onClick="if(!confirm(\''.$msgFinish.'\')) return false;" name="submit-result" value="'.__('Validate', 'sponsorpress').'" />';
                                                        echo '</form></div>';
                                                        
                                                    } else {
                                                    
                                                        echo '<div class="clear"></div>';
                                                        if( $_GET["realise_d"] == 1 ) {
                                                            echo '<div class="wpspo-confirm">'.__('Your result has been validated. Thanks!', 'sponsorpress').'</div>';
                                                        }
                                                        echo '<div><small>';
                                                        printf(__('Results: %s', 'sponsorpress'), wpspo_trim_zeros($participant->users_realise));
                                                        echo ' '.stripslashes($valueOptions->text_mode_defis).'</small></div>';
                                                        
                                                    }
                                                    
                                                } else if($verifiDejaSponsor==1) {
                                                    
                                                    echo '<div class="clear"></div>';
                                                    echo '<div>';
                                                    echo '<small>';
                                                    printf(__('You already sponsor %s', 'sponsorpress'), $auteurName);
                                                    if ( $post->post_status=='archive' ) {
                                                        echo '<br />';
                                                        printf(__('This challenge is over. Thank you finalize your pledge here: %s', 'sponsorpress'), '<a href="'.get_permalink(WPSPO_ID_COMPTE).'#mespromesses">'.__('my account', 'sponsorpress').'</a>');
                                                    }
                                                    if($valueOptions->mode_defis==2) {
                                                        echo '<br />';
                                                        $linkDonate = get_post_meta($idProjet, 'wpspo_boxlinkdonate', true);
                                                        printf( __('Donate now! %s ', 'sponsorpress'), '<a href="'.$linkDonate.'" target="_blank" style="text-decoration:underline;">'.__('Go to this link', 'sponsorpress').'</a>' );
                                                    }
                                                    echo '</small></div>';
                                                }
                                            }
                                            echo '</span>';
                                        echo '</div>';
                                    }
                                    echo '</div>';
                                    
                                } else {
                                    echo __('There is no participant.', 'sponsorpress');
                                }
                                ?>
                    </div>
                </div>
            </article>
            <div class="clear espace10">&nbsp;</div>
        <?php endwhile; ?>

    <?php if($projetStatus=='publish') { comments_template( '', true ); } ?>

    <?php endif; ?>

</div><!-- #content -->

<?php get_sidebar(); ?>
<?php get_footer(); ?>


